package com.chj.comp.common.auth.controller;

import com.chj.comp.common.auth.security.config.AuthorizationServerConfig;
import com.chj.comp.common.core.constant.CommonConstant;
import com.chj.comp.common.core.util.Result;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ：cuihui
 * @date ：Created in 2023/3/30
 * @description：授权码模式、简单模式
 * @modified By：
 */
@Controller
@SessionAttributes("authorizationRequest")
public class AuthGrantController {

    /**
     * 自定义授权确认页面（适用授权码模式、简单模式）
     * 需在{@link AuthorizationServerConfig#configure(AuthorizationServerEndpointsConfigurer)}中配置
     * @param param
     * @return
     */
    @RequestMapping("/custom/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> param) {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) param.get("authorizationRequest");
        ModelAndView model = new ModelAndView();
        model.setViewName("base-grant");
        model.addObject("clientId", authorizationRequest.getClientId());
        model.addObject("action", CommonConstant.AUTH_URI + CommonConstant.AUTHORIZE_URI);
        Set<String> scopes = authorizationRequest.getScope();
        scopes = scopes.stream().map(s -> "scope." + s).collect(Collectors.toSet());
        model.addObject("scopes", scopes);

        return model;
    }

    /**
     * 回调地址获取授权码（授权码模式）
     * @param request
     * @return
     */
    @GetMapping(value = "/getAuthCodeCallBack")
    @ResponseBody
    public Result getAuthCodeCallBack(HttpServletRequest request) {
        try {
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("code", code);
            resultMap.put("state", state);
            return Result.ok(resultMap, null);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
}
